import Vuex from "vuex";
import Vue from "vue";
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    todos: [], //事项列表
  },
  mutations: {
    SET_TODOS(state, todos) {
      state.todos = todos;
    },
  },
  actions: {
    //添加todolist
    addTodos({ commit, state }, params) {
      let list = state.todos;
      list.unshift(params);
      commit("SET_TODOS", list);
    },
    //删除
    delTodos({ commit, state }, id) {
      let list = state.todos.filter((todo) => {
        return todo.id !== id;
      });
      commit("SET_TODOS", list);
    },

    //勾选
    changeTodo({ commit, state }, params) {
      const index = state.todos.findIndex((todo) => {
        return todo.id === params.id;
      });
      let list = state.todos;
      if (Object.prototype.hasOwnProperty.call(params.todo, "done")) {
        list[index].done = params.todo.done;
        commit("SET_TODOS", list);
      }
      if (Object.prototype.hasOwnProperty.call(params.todo, "name"))
        list[index].name = params.todo.name;
      commit("SET_TODOS", list);
    },

    //清空
    resetTodos({ commit }) {
      commit("SET_TODOS", []);
    },
  },
  getters: {
    todos: (state) => state.todos,
  },
  //npm i vuex-persistedstate
  plugins: [
    createPersistedState({
      storage: window.sessionStorage, // 同localStorage相同，只是将vuex的所有值存储到sessionStorage中
    }),
  ],
});

export default store;
